package com.hdphone.zljutils.impl;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;

import com.hdphone.zljutils.ZljUtils;
import com.hdphone.zljutils.inter.IApkUtil;

import java.io.File;

import androidx.core.content.FileProvider;

/**
 * @author sq
 * @date 2020/10/19
 * @describe
 */
public class ApkUtilImpl implements IApkUtil {

    private final String TAG = getClass().getSimpleName();

    @Override
    public void installApk(String path) {
        if (!TextUtils.isEmpty(path)) {
            try {
                File file = new File(path);
                if (file.exists()) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        //大于等于8.0
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                    Uri apkUri = getUriFromFile(file);
                    String mimeType = "application/vnd.android.package-archive";
                    intent.setDataAndType(apkUri, mimeType);
                    ZljUtils.getApp().startActivity(intent);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private Uri getUriFromFile(File file) {
        String authority = "com.huodao.hdphone.fileprovider";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            // Android 7.0 以下
            return Uri.fromFile(file);
        } else {
            // Android 7.0 及以上
            return FileProvider.getUriForFile(ZljUtils.getApp(), authority, file);
        }
    }
}
